package org.adit.spring.hibernate.infra;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.OutputStream;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.w3c.dom.Document;
import org.w3c.tidy.Tidy;
import org.xhtmlrenderer.pdf.ITextRenderer;

import com.lowagie.text.DocumentException;

public class PdfFilter implements Filter {
	
	private FilterConfig filterConfig;
	private ServletContext servletContext;

	public void destroy() {
		this.filterConfig = null;
	}

	public void doFilter(ServletRequest _request, ServletResponse _response,
			FilterChain chain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) _request;
        HttpServletResponse response = (HttpServletResponse) _response;

        String action = request.getParameter("action");
        
        if ("imprimir".equals(action)) {
        	System.out.println(String.format("action [%s]", action));
        	// gerar PDF
            System.out.println(String.format("gerando PDF"));
            // cria response wrapper
            ByteArrayOutputStream buffer = new ByteArrayOutputStream();
            CacheResponseWrapper responseWrapper = new CacheResponseWrapper(response, buffer);

            chain.doFilter(_request, responseWrapper);

            // servletresponse para o cliente
            response.setContentType("application/pdf");
            OutputStream outputStream = response.getOutputStream();

            Tidy tidy = new Tidy();
            Document doc = tidy.parseDOM(new ByteArrayInputStream(buffer.toByteArray()), outputStream);
            ITextRenderer renderer = new ITextRenderer();
            renderer.setDocument(doc, null);
            renderer.layout();
            try {
                renderer.createPDF(outputStream);

            } catch (DocumentException ex) {
                throw new IOException(ex);
            }

        } else {
            chain.doFilter(_request, _response);
        }		
	}

	public void init(FilterConfig filterConfig) throws ServletException {
		this.filterConfig = filterConfig;
		this.servletContext = filterConfig.getServletContext();
	}
}
